// pages/voteActiveDetail/voteActiveDetail.js
import api from "../../config/api";
import {
    shareOptions,
} from "../../utils/access";
import request from "../../utils/request";
import {
    getBarAndTitleHeight,
    getXsScreen,
    getStorage,
    setStorage,
    goBack,
    countDown
} from "../../utils/utils";
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 信号栏是否有背景
        hasBg: false,
        // 信号栏高度
        ...getBarAndTitleHeight(),
        // 是否是小屏幕尺寸
        ...getXsScreen(),
        //倒计时时间
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        // 选中tab标签
        currentTab: 0,
        // 小区id
        id: '',
        // 详情数据
        detail: {},
        // 贡献者数据
        userList: [],
        // 帖子数据(默认排序)
        dynamicTimeList: [],
        // 人气排行
        dynamicVoteList: [],
        list: [],
        // 投票信息
        voteInfo: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        if (options.scene) {
            var scene = decodeURIComponent(options.scene);
            if (scene) {
                let arr = scene.split("=");
                console.log("scene:", arr[0], "=", arr[1]);
                this.setData({
                    id: arr[1]
                })
            }
        } else {
            this.setData({
                id: options.id
            })
        }
        if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
        this.getDetail()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.handleModal = this.selectComponent('#handleModal')
        this.shareModal = this.selectComponent('#shareModal')
        this.posterModal = this.selectComponent('#poster')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getTime()
        if (this.data.id) {
            this.getDetail()
        }
    },
    // tab切换
    switchTab(e) {
        this.setData({
            currentTab: e.detail.current
        });
        this.getDetail()
    },
    // 滚动切换标签
    switchNav(e) {
        let cur = e.currentTarget.dataset.current;
        if (this.data.currentTab == cur) {
            return false;
        } else {
            this.setData({
                currentTab: cur
            });
        }
    },
    // 返回
    back() {
        goBack()
    },
    // 获取详情
    async getDetail() {
        let {
            id: communityId,
            currentTab
        } = this.data
        let res = await request.get(api.communityVoteDetail, {
            communityId
        }, {
            loading: false
        })
        if (res.httpStatus === 200) {
            res.data.userList.forEach(item=>{
                item.nickName = item.nickName.length>5? item.nickName.slice(0,5)+'...' : item.nickName
            })
            this.setData({
                detail: res?.data,
                userList: res?.data?.userList,
                list: currentTab === 1 ? res?.data?.dynamicVoteList : res?.data?.dynamicTimeList
            })
        }
    },
    // 获取活动时间
    async getTime() {
        let res = await request.get(api.voteTime, {}, {
            loading: false
        })
        if (res.httpStatus === 200) {
            this.setData({
                timeInfo: res.data
            })
            countDown(res.data.startDate + ' ' + '00:00:00', res.data.endDate + ' ' + '00:00:00', this)
        }
    },
    // 预览图片
    previewImg(e) {
        let src = e.currentTarget.dataset.src
        wx.previewImage({
            urls: [src]
        })
    },
    // 投票操作
    async voteHandle(e) {
        if (this.loading) return
        this.loading = true
        if (!app.isLogin()) {
            setStorage('redirectPath', `/pages/voteActiveDetail/voteActiveDetail?id=${this.data.id}`)
            app.login()
            this.loading = false
            return
        }
        this.setData({
            voteInfo: {}
        })
        let id = e.currentTarget.dataset.id
        let res = await request.post(`${api.voteHandle}/${id}`, {}, {
            loading: false
        })
        if (res.httpStatus === 200) {
            if (res.data?.type === 0) {
                wx.vibrateShort({
                    type: 'medium'
                })
            }
            this.setData({
                voteInfo: res.data || {}
            }, () => {
                this.handleModal.show()
            })
            this.getDetail()
        }
        this.loading = false
    },
    // 分享点击
    async shareClick() {
        let {
            communityName,
            communityId,
            picUrl
        } = this.data.detail
        if (app.isLogin()) {
            let fileData = await request.get(api.qrcodeImage, {
                page: 'pages/voteActiveDetail/voteActiveDetail',
                scene: 'inviteId=' + communityId
            }, {
                responseType: 'arraybuffer'
            })
            console.log('fileData',fileData);
            this.shareModal.show()
            this.initShareImg(communityName, picUrl, fileData)
        } else {
            setStorage('redirectPath', `/pages/voteActiveDetail/voteActiveDetail?id=${communityId}`)
            app.login()
        }
    },
    // 初始化分享图
    initShareImg(communityName, picUrl, fileData) {
        const fileManager = wx.getFileSystemManager()
        const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`
        console.log(filePath)
        fileManager.writeFileSync(filePath, fileData, 'binary')
        this.posterModal.init(async (vm) => {
            // 背景图
            await vm.image({
                src: 'https://image-classify.daieco.com/kejian-quanzi/MFXsKZqLCdAHd2a0ffee05d7248b82efb7a9aace76ca.png',
                width: 648,
                height: 1180,
            })
            // 小区图片
            await vm.image({
                src: picUrl,
                top: 372,
                left: 22,
                width: 486,
                height: 364,
                rotate: -7,
            })
            // 相框
            await vm.image({
                src: 'https://image-classify.daieco.com/kejian-quanzi/5ikoT8H6zzU4e68cd23c7c588ad8640889b96e3d45f2.png',
                width: 620,
                height: 526,
                top: 280,
                left: 28
            })
            // 小区名称
            vm.text({
                content: communityName,
                left: 258,
                top: 785,
                fontSize: 36,
                rotate: -7,
                color: '#1D935C',
                textAlign: 'center',
                fontWeight: 'bold',
            })
            // 助力文案
            vm.text({
                content: '识别二维码，为TA投票助力',
                left: 194,
                top: 936,
                fontSize: 32,
                color: '#0E0E0E',
                fontWeight: 'bold',
            })
            // 小区二维码
            await vm.image({
                src: filePath,
                width: 100,
                height: 100,
                top: 874,
                left: 60,
                radius: 6
            })
        })
    },
    // 保存分享图片
    saveImg() {
        this.posterModal?.savePicture()
    },
    // 关闭投票操作弹窗
    handleModalCancel() {
        this.handleModal.hide()
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        // 清除定时器
        clearInterval(this.timeInterval)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // 清除定时器
        clearInterval(this.timeInterval)
    },

    // 页面滚动事件
    onPageScroll(e) {
        this.setData({
            hasBg: e?.scrollTop > 20,
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: async function (e) {
        const userId = getStorage('userId') || ''
        this.handleModal.hide()
        // 分享获取抽奖次数
        request.get(api.voteShare, {}, {
            loading: false
        })
        return shareOptions('default', e, '2022年度最干净小区评选开始~', `/pages/voteActiveDetail/voteActiveDetail?id=${this.data.id}&inviteData=${userId}`, 'https://image-classify.daieco.com/kejian-quanzi/hQcQDvv4Kndm40abd21005c2dbfb53fb4bfb2a036813.png')
    }
})